package pers.elonnsu.springbootmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import pers.elonnsu.springbootmall.common.Constant;
import pers.elonnsu.springbootmall.exception.MallException;
import pers.elonnsu.springbootmall.exception.MallExceptionEnum;
import pers.elonnsu.springbootmall.model.dao.ProductMapper;
import pers.elonnsu.springbootmall.model.pojo.Product;
import pers.elonnsu.springbootmall.model.query.ProductListQuery;
import pers.elonnsu.springbootmall.model.request.AddProductReq;
import pers.elonnsu.springbootmall.model.request.ProductListReq;
import pers.elonnsu.springbootmall.model.vo.CategoryVO;
import pers.elonnsu.springbootmall.service.CategoryService;
import pers.elonnsu.springbootmall.service.ProductService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    private ProductMapper productMapper;
    @Resource
    private CategoryService categoryService;

    /**
     * 后台：添加商品
     *
     * @param addProductReq 添加商品请求对象
     */
    @Override
    public void add(AddProductReq addProductReq) {
        Product product = new Product();
        BeanUtils.copyProperties(addProductReq, product);
        Product productOld = productMapper.selectByName(addProductReq.getName());
        if (productOld != null) {
            throw new MallException(MallExceptionEnum.NAME_EXISTED);
        }
        int count = productMapper.insertSelective(product);
        if (count == 0) {
            throw new MallException(MallExceptionEnum.INSERT_FAILED);
        }
    }

    @Override
    public void update(Product updateProduct) {
        Product productOld = productMapper.selectByName(updateProduct.getName());
        // 同名且不同id，不能修改
        if (productOld != null && !productOld.getId().equals(updateProduct.getId())) {
            throw new MallException(MallExceptionEnum.NAME_EXISTED);
        }
        int count = productMapper.updateByPrimaryKeySelective(updateProduct);
        if (count == 0) {
            throw new MallException(MallExceptionEnum.UPDATE_FAILED);
        }
    }

    @Override
    public void delete(Integer id) {
        Product productOld = productMapper.selectByPrimaryKey(id);
        // 查不到该记录，无法删除
        if (productOld == null) {
            throw new MallException(MallExceptionEnum.DELETE_FAILED);
        }
        int count = productMapper.deleteByPrimaryKey(id);
        if (count == 0) {
            throw new MallException(MallExceptionEnum.UPDATE_FAILED);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateSellStatus(Integer[] ids, Integer sellStatus) {
        int count = productMapper.batchUpdateSellStatus(ids, sellStatus);
        if (count != ids.length) {
            throw new MallException(MallExceptionEnum.DELETE_FAILED);
        }
    }

    @Override
    public PageInfo<Product> listForAdmin(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> products = productMapper.selectAllProductForAdmin();
        return new PageInfo<>(products);
    }

    @Override
    @Cacheable(value = "listProductForCustomer")
    public PageInfo<Product> listForCustomer(ProductListReq productListReq) {
        ProductListQuery productListQuery = new ProductListQuery();

        // 检查分页参数
        if (productListReq.getPageNum() == null || productListReq.getPageNum() < 1) {
            productListReq.setPageNum(1);
        }
        if (productListReq.getPageSize() == null || productListReq.getPageSize() < 1) {
            productListReq.setPageSize(10);
        }

        // 搜索处理
        if (!StringUtils.isEmpty(productListReq.getKeyword())) {
            String keyword = "%" + productListReq.getKeyword() + "%";
            productListQuery.setKeyword(keyword);
        }
        // 目录处理：如果查询某个目录下的商品，不仅是需要查出该目录下的，还要查询
        // 其子目录下的所有商品，拿到一个目录id的列表集合
        if (productListReq.getCategoryId() != null) {
            List<CategoryVO> categoryVOList = categoryService.listCategoryForCustomer(productListReq.getCategoryId());
            List<Integer> categoryIds = new ArrayList<>();
            getCategoryIdsFromVOList(categoryVOList, categoryIds);
            productListQuery.setCategoryIds(categoryIds);
        }

        // 排序处理
        String orderBy = productListReq.getOrderBy();
        if (Constant.ProductListOrderBy.PRICE_ORDER_ENUM.contains(orderBy)) {
            PageHelper.startPage(productListReq.getPageNum(), productListReq.getPageSize(), orderBy);
        } else {
            PageHelper.startPage(productListReq.getPageNum(), productListReq.getPageSize());
        }
        List<Product> products = productMapper.selectAllProductForCustomer(productListQuery);
        return new PageInfo<>(products);
    }

    @Override
    public Product detail(Integer id) {
        return productMapper.selectByPrimaryKey(id);
    }

    /**
     * 递归Helper：获取categoryVOList 中各个category的id
     */
    private void getCategoryIdsFromVOList(List<CategoryVO> categoryVOList, List<Integer> categoryIds) {
        if (categoryVOList != null) {
            categoryVOList.forEach(categoryVO -> {
                categoryIds.add(categoryVO.getId());
                getCategoryIdsFromVOList(categoryVO.getChildCategory(), categoryIds);
            });
        }
    }
}
